<template>
    <van-nav-bar title="地址列表" left-text="返回" left-arrow @click-left="onClickLeft" />
    <div>
        <van-address-list v-model="chosenAddressId" default-tag-text="默认" :list="list" @add="onAdd" @edit="onEdit"
            @select="selectAddress" />
    </div>
</template>

<script lang="ts" setup>
import { ref, toRef } from 'vue';
import router from '@/router'
import { useRoute } from 'vue-router'
const route = useRoute()

import { update,ress  } from '../api/map'
import {updateOrderAddress} from '../api/order'
import { GoodStore } from "../store/good";
import { useCommon } from '@/hooks/useCommon'
const { goback } = useCommon()
const goodStore = GoodStore()
const addressList = toRef(goodStore, 'addressList')   // toRef 得到的 ref 数据  value 
const chooseAddress = toRef(goodStore, 'chooseAddress')    // 已经选择的地址 



const list = ref()
const userid: any = localStorage.getItem('id')
const onClickLeft = () => history.back();
const chosenAddressId = ref('');
const onAdd = () => {
    router.push({ name: 'addressedit' })
};
const onEdit = (item, index) => {
    console.log(item)
    router.push(`/addressupdate/${index}`)
}

//  地址列表
ress(userid).then(res => {
    console.log(res)
    list.value = res.data.map((item, index) => {
        item.address = item.province + item.city + item.county + item.addressDetail;
        item.id = item.addressid;
        // item.id = index;    
        return item;
    })
})



//  切换
const selectAddress = async (value) => {
    if (route.query.from) {
        // gotoOnePage('/order-detail')
        let res: Result = await updateOrderAddress({
            userid,
            time: route.query.time,
            ...value
        })
        if (res.code == '200') {
            goback()
        }

    } else {
        update({
            addressid: item.addressid,
            userid,
            isDefault: true
        }
        ).then(res => {
            console.log(res)
            goback()
        })

        let isDefaultList = addressList.value.filter(a => a.isDefault)  // 默认的
        isDefaultList.forEach(async (v) => {
            let res = await update({
                addressid: v.addressid,
                userid,
                isDefault: false
            })
        })
    }

}

</script>